package com.gljx.shiro;

import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.ProcessEngines;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.gljx.constant.AjaxStatusCode;
import com.gljx.constant.Constant;
import com.gljx.spring.manage.exception.IncorrectCaptchaException;
import com.gljx.util.AjaxUtil;
import com.gljx.web.Entity.User;
import com.gljx.web.service.SysService;

import org.apache.log4j.Logger;

/**
 * 登录请求+验证码拦截器
* @author LiXiang
* @date 2017年9月28日 上午10:25:27 
*
 */
public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter {

    public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
    private  Logger logger = Logger.getLogger(getClass());
		@Autowired(required = true)
		private SysService sysService;
    private String captchaParam = DEFAULT_CAPTCHA_PARAM;

    /*public void onLoginFailure(){

    }*/
    public CaptchaFormAuthenticationFilter() {
	    }

    @Override
    /**
     * 登录验证
     */
    protected boolean executeLogin(ServletRequest request,
                                   ServletResponse response) throws Exception {
        CaptchaUsernamePasswordToken token = createToken(request, response);
        try {
                /*图形验证码验证*/
                doCaptchaValidate((HttpServletRequest) request, token);

	            //登录信息
                Subject subject = getSubject(request, response);
                subject.login(token);//正常验证

                logger.info(token.getUsername() + "登录成功");

	            request.removeAttribute("userName");
	            request.removeAttribute("password");
	            request.removeAttribute("remember");

                return onLoginSuccess(token, subject, request, response);
        }catch(IncorrectCaptchaException e){
	        	//验证码错误，只将异常存入返回前台的数据
                return onLoginFailure(token, e, request, response);
        }catch (AuthenticationException e) {
	        	e.printStackTrace();
	        	request.setAttribute("userName", (String)token.getPrincipal());
	            request.setAttribute("password", String.valueOf(token.getPassword()));
	            request.setAttribute("remember", token.getRemember());

                logger.info("##" + token.getUsername() + "##" + token.getHost() + "##" + "登录失败--" + e);
                return onLoginFailure(token, e, request, response);
        }catch (Exception e){
	        	e.printStackTrace();
                logger.info("##" + token.getUsername() + "##" + token.getHost() + "##" + "登录失败，未知异常--" + e);
                return false;
        }
	    }

    /**
     *  验证码校验
     * @param request
	    * @param token
	    * @author LiXiang  @date 2017年10月19日 上午9:40:11
	     */
    protected void doCaptchaValidate(HttpServletRequest request,
                                     CaptchaUsernamePasswordToken token) {
        //session中的图形码字符串
            /*String captcha = (String) request.getSession().getAttribute(
                    com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			System.out.println("------------"+captcha+"----------");
			//比对
	        if (captcha != null && !captcha.equalsIgnoreCase(token.getCaptcha())) {*/
	        	request.setAttribute("userName", (String)token.getPrincipal());
	            request.setAttribute("password", String.valueOf(token.getPassword()));
	            request.setAttribute("remember", token.getRemember());
            /*    throw new IncorrectCaptchaException("验证码错误！");
	        }*/
	    }

    /**
	     * 创建比较对象
	     */
    @Override
    protected CaptchaUsernamePasswordToken createToken(ServletRequest request,
                                                       ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        //String captcha = getCaptcha(request);
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);

	        //拓展增加验证码参数,放入自定义的管理用户组中
        return new CaptchaUsernamePasswordToken(username,
                password.toCharArray(), rememberMe, host/*, captcha*/);
    }
	  
	    public String getCaptchaParam() {  
	        return captchaParam;  
	    }
	  
	    public void setCaptchaParam(String captchaParam) {  
	        this.captchaParam = captchaParam;  
	    }
	  
	    /*protected String getCaptcha(ServletRequest request) {  
	        return WebUtils.getCleanParam(request, getCaptchaParam());  
	    }*/
	      
	    //保存异常对象到request  
	    @Override  
	    protected void setFailureAttribute(ServletRequest request,  
	            AuthenticationException ae) {  
	        request.setAttribute(getFailureKeyAttribute(), ae);  
	    }  
	     /**
	      * 重写shiro登录成功跳转逻辑
	      */
	    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
	    	/**
	    	 *记住我 
	    	 */
	    	//boolean rememberMe = Boolean.valueOf(request.getParameter("rememberuser"));
	    	/**
	    	 * 用户令牌
	    	 */
	    	/*CaptchaUsernamePasswordToken token = createToken(request, response);
	    	if(rememberMe){
	    		MyRememberMe.rememberCookie(token, request, response);
	    	}else{
	    		MyRememberMe.removeCookie(token, request, response);
	    	}*/
	    	String fallbackUrl = getSuccessUrl();
	        String successUrl = null;
	        boolean contextRelative = true;
	        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
	        
	        if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
	            successUrl = savedRequest.getRequestUrl();
	            contextRelative = false;
	        }

	        if (successUrl == null) {
	            successUrl = fallbackUrl;
	        }

	        if (successUrl == null) {
	            throw new IllegalStateException("Success URL not available via saved request or via the " +
	                    "successUrlFallback method parameter. One of these must be non-null for " +
	                    "issueSuccessRedirect() to work.");
	        }
	        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
	        String url = httpServletRequest.getContextPath();
	        if((url+Constant.Longin_html).equals(successUrl)){
	        	successUrl=(url+Constant.Index_html);
	        }
	        if(("/").equals(successUrl)){
	        	successUrl="/"+Constant.UrlAfter+"/"+Constant.Index_html;
	        }
	        if(("/DrivingSys/").equals(successUrl)){
	        	successUrl=("/"+Constant.UrlAfter+"/"+Constant.UrlAfter+"/"+Constant.Index_html);
	        }
	        //用户
			String username= (String) SecurityUtils.getSubject().getPrincipal(); 
			User user = sysService.selectByPrimaryKey(username);
			Session session = SecurityUtils.getSubject().getSession();
			if(user !=null){

                User user1 = new User();

				session.setAttribute(Constant.UserId_session,user.getId());
				session.setAttribute(Constant.CompanyId_session,user.getFcompanyid());
				session.setAttribute(Constant.CompanyName_session, user.getCompanyName());
				session.setAttribute(Constant.CompanyLFnumber_session, user.getCompanyLongFnumber());
                session.setAttribute(Constant.User_Fid_session, user.getFid());


                user1.setFid(user.getFid());//fid
                user1.setUserName(user.getUserName());//账号
                user1.setName(user.getUserName());//用户名
                user1.setFcompanyid(user.getFcompanyid());//公司ID
				user1.setCompanyLongFnumber(user.getCompanyLongFnumber());//公司长number
				user1.setCompanyName(user.getCompanyName());
                session.setAttribute("user", user1);

			}
	        //System.out.println("原本我要访问这里："+successUrl);
	        WebUtils.issueRedirect(request, response, successUrl, null, contextRelative);
	    }
	//原FormAuthenticationFilter的认证方法
	//现在用来处理无权限访问和超时
	@Override
	protected boolean onAccessDenied(ServletRequest request,
									 ServletResponse response) 
											 			throws Exception {
		if (isLoginRequest(request, response)) {//正常请求
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {//无验证，包括超时和无权限
            HttpServletRequest httpRequest = WebUtils.toHttp(request);
            
            if (AjaxUtil.isAjax(httpRequest)) {//这里判断是否ajax
                
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);  
                httpServletResponse.sendError(AjaxStatusCode.HTTP_STATUS_SESSION_EXPIRE);
                 
                return false;
    
            } else {  
                saveRequestAndRedirectToLogin(request, response); 
            }  

            return false;
        }
    }
}
